var util=require("../../lib/utils.js")
Page({
  data: {
    originalImage: '',
    isBlackFirst: false,
    isHave: false,
    toPic: '',
    originalToPic: '',
    height: '',
    width: '',
    base64Data:'',
    startHeight:0,
  },

  onLoad: function (options) {
    var path = options.path
    var base64Image = decodeURIComponent(wx.getStorageSync('image'))
    var originalBase64Image = decodeURIComponent(wx.getStorageSync('originalImage'))
    this.setData({
      originalImage: path,
      base64Data:base64Image
    })
    var screenHeight = wx.getSystemInfoSync().screenHeight
    var screenWidth = wx.getSystemInfoSync().screenWidth
    console.log("====", JSON.stringify(screenHeight))
    this.setData({
      height: screenHeight - 100,
      width: screenWidth - 20
    })
    this.x = 0
    var that = this
    wx.getImageInfo({
      src: this.data.originalImage,
      success: res => {
        console.log("success", JSON.stringify(res))
        that.data.originalWidth = that.data.imageWidth = res.width
        that.data.originalHeight = that.data.imageHeight = res.height
        wx.createSelectorQuery()
          .select('#canvas')
          .fields({
            node: true,
            size: true,
          })
          .exec(that.init.bind(that))
      }, fail: res => {
        console.log("fail", JSON.stringify(res))
      }
    })
    util.base64src('0004.png', originalBase64Image).then(function (res) {
      console.log("base64src=====" + JSON.stringify(res))
      that.data.originalToPic = res
      that.data.isBlackFirst = true
    })
    util.base64src('0003.png', base64Image).then(function (res) {
      console.log("base64src=003====" + JSON.stringify(res))
      that.data.toPic = res
      that.data.isHave = true
    })
  },
  onUnload:function(){
    util.onDeletePic("0004.png")
    util.onDeletePic("0003.png")
  },
  bindSeePic:function(){
    wx.navigateTo({
      url: '/pages/img/img',
    })
  },
  bindSave: function () {
    var that = this
    var that = this
    wx.getSetting({
      success: function (res) {
        if (res.authSetting["scope.writePhotosAlbum"]) {
          that.saveFile()
        } else {
          wx.authorize({
            scope: "scope.writePhotosAlbum",
            success: function (e) {
              that.saveFile()
              console.log("===", JSON.stringify(e))
            },
            fail: function (e) {
              console.log("===", JSON.stringify(e))
            }
          });
        }
      },
      fail: function (e) {
        console.log("===", JSON.stringify(e))
      }
    });
  },
  saveFile: function () {
    var n = new Date().getTime()
    var t = wx.getFileSystemManager()
    t.writeFile({
      filePath: wx.env.USER_DATA_PATH + "/idphoto_" + n + ".png",
      data: this.data.base64Data,
      encoding: "base64",
      success: function (e) {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + "/idphoto_" + n + ".png",
          success: function (e) {
            wx.showModal({
              title: "保存成功",
              showCancel: false
            });
          },
          fail: function (e) {
            e.errMsg.includes("cancel") || wx.showModal({
              title: e.errMsg,
              showCancel: false
            });
          },
          complete: function () {
            wx.hideLoading();
          }
        });
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },
  init(res) {
    const width = res[0].width
    const height = res[0].height
    const canvas = res[0].node
    const ctx = canvas.getContext('2d')
    const dpr = wx.getSystemInfoSync().pixelRatio
    canvas.width = width * dpr
    canvas.height = height * dpr
    this.data.canvasWidth = width
    this.data.canvasHeight = height
    ctx.scale(dpr, dpr)
    var wh = this.data.imageWidth / this.data.imageHeight
    this.data.imageWidth = this.data.canvasWidth
    this.data.imageHeight = this.data.imageWidth / wh
    if(this.data.canvasHeight>this.data.imageHeight){
      this.data.startHeight=(this.data.canvasHeight-this.data.imageHeight)/2
    }
    this.x = this.data.imageWidth / 2

    const renderLoop = () => {
      this.render(canvas, ctx)
      canvas.requestAnimationFrame(renderLoop)
    }
    canvas.requestAnimationFrame(renderLoop)

    const imgMap = canvas.createImage()
    imgMap.onload = () => {
      console.log("imgMap======" + imgMap)
      this._imgMap = imgMap
    }
    imgMap.src = '../../images/middle.png'
  },
  render(canvas, ctx) {
    if (this.x > this.data.canvasWidth || this.x < 0) return
    if (this.data.isBlackFirst) {
      const img = canvas.createImage()
      img.onload = () => {
        this._img = img
      }
      img.src = this.data.originalToPic
      this.data.isBlackFirst = false
    }
    if (this.data.isHave) {
      const imgTo = canvas.createImage()
      imgTo.onload = () => {
        this._imgTo = imgTo
      }
      imgTo.src = this.data.toPic
      this.data.isHave = false
    }
    ctx.clearRect(0, 0, this.data.canvasWidth, this.data.canvasHeight)
    this.drawCar(ctx)
  },
  drawCar(ctx) {
    if (this._img) {
      ctx.drawImage(this._img, 0, this.data.startHeight, this.data.imageWidth, this.data.imageHeight)
    }
    ctx.lineWidth = 1
    ctx.strokeStyle = 'white'
    ctx.strokeRect(10, this.data.canvasHeight - 40, 80, 30)
    ctx.font = "16px cursive"
    ctx.fillStyle = "white"
    ctx.fillText('优化前', 30, this.data.canvasHeight - 20)

    if (this._imgTo) {
      var x = (this.x * this.data.originalWidth) / this.data.imageWidth
      ctx.drawImage(this._imgTo, x, 0, this.data.originalWidth, this.data.originalHeight, this.x, this.data.startHeight, this.data.imageWidth, this.data.imageHeight)
      ctx.restore()
      ctx.lineWidth = 1
      ctx.strokeStyle = 'white'
      ctx.strokeRect(this.x + 10, this.data.canvasHeight - 40, 80, 30)
      ctx.font = "16px cursive"
      ctx.fillStyle = "white"
      ctx.fillText('优化后', this.x + 30, this.data.canvasHeight - 20)
    }
    ctx.restore()
    ctx.beginPath()
    ctx.lineWidth = 3
    ctx.strokeStyle = "white"
    ctx.moveTo(this.x, 0)
    ctx.lineTo(this.x, this.data.canvasHeight)
    ctx.stroke()
    var x = this.x - 15
    var y = (this.data.canvasHeight - 30) / 2
    if (this._imgMap) {
      ctx.drawImage(this._imgMap, x, y, 30, 30)
    }
  },
  bindTouch: function (e) {
    console.log(JSON.stringify(e))
    this.x = e.changedTouches[0].x
    console.log(e.changedTouches[0].x)
    console.log(e.changedTouches[0].y)
  },
  bindTap: function (e) {
    console.log(JSON.stringify(e))
    this.x = e.changedTouches[0].clientX
    console.log(e.changedTouches[0].clientX)
  }
})